package com.zhb.austapp.activity;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;

import com.zhb.austapp.R;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;
import android.widget.Toast;


import com.google.gson.Gson;
import com.zhb.austapp.bean.ResultBean;
import com.zhb.austapp.utils.APIConfig;

import org.json.JSONException;
import org.json.JSONObject;

import java.io.IOException;

import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.MediaType;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.RequestBody;
import okhttp3.Response;

public class RegisterActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText et_name;
    private EditText et_nicke;
    private EditText et_phonr;
    private EditText et_password;
    private EditText et_comfirmpassword;
    private EditText et_code;

    private Button btn_register;
    private Button btn_login;
    private Button btn_sendSMS;

    private OkHttpClient client = new OkHttpClient();
    private Intent intent = null;

    String sex = "";
    private Handler handler = new Handler() {
        @Override
        public void handleMessage( Message msg) {
            super.handleMessage(msg);
            if (msg.what==0) {
                String resultStr = (String) msg.obj;
                Log.i("获取返回的信息：",resultStr);
                final ResultBean resultBean = new Gson().fromJson(resultStr,ResultBean.class);
                int resultCode = resultBean.getCode();
                if (resultCode==200){
                    Toast.makeText(getApplicationContext(),"注册成功："+resultStr,Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),"注册失败："+resultStr,Toast.LENGTH_LONG).show();
                }

            }else if(msg.what==1){
                String resultStr = (String) msg.obj;
                Log.i("获取返回的信息：",resultStr);
                final ResultBean resultBean = new Gson().fromJson(resultStr,ResultBean.class);
                int resultCode = resultBean.getCode();
                if (resultCode==0 && resultBean.isSuccess()){
                    Toast.makeText(getApplicationContext(),"短信发送成功！",Toast.LENGTH_LONG).show();
                } else {
                    Toast.makeText(getApplicationContext(),"短信发送失败！"+resultStr,Toast.LENGTH_LONG).show();
                }
            }
        }
    };

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_register);
        initView();
    }

    private void initView() {
        et_name = (EditText) findViewById(R.id.et_name);
        et_nicke = (EditText) findViewById(R.id.et_nicke);
        et_phonr = (EditText) findViewById(R.id.et_phone);
        et_password = (EditText) findViewById(R.id.et_password);
        et_comfirmpassword=findViewById(R.id.et_comfirmpassword);
        et_code =findViewById(R.id.et_smscode);
        btn_register = (Button) findViewById(R.id.btn_register);
        btn_login = (Button) findViewById(R.id.btn_login);
        btn_sendSMS = (Button) findViewById(R.id.btn_sendSMS);

        btn_register.setOnClickListener(this);
        btn_login.setOnClickListener(this);
        btn_sendSMS.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_sendSMS:
                sendSmsCode();
                break;
            case R.id.btn_register:
                Register();
                break;
            case R.id.btn_login:
                intent = new Intent(getApplicationContext(),LoginActivity.class);
                startActivity(intent);
                break;
        }
    }

    private void sendSmsCode() {
        String phone = et_phonr.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入你的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        final JSONObject jsonObject = new JSONObject();
//        {mobile: "18055429927", smsmode: "1"}
        try {
            jsonObject.put("mobile",phone);
            jsonObject.put("smsmode","1");
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        final RequestBody requestBody =RequestBody.create(mediaType,jsonObject.toString());
        Request request = new Request.Builder()
                .post(requestBody)
                .url(APIConfig.RegisterSMS)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure", "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                Message msg = new Message();
                msg.what=1;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        });
    }

    private void Register() {
        // validate
        String name = et_name.getText().toString().trim();
        if (TextUtils.isEmpty(name)) {
            Toast.makeText(this, "请输入用户名", Toast.LENGTH_SHORT).show();
            return;
        }

        String nicke = et_nicke.getText().toString().trim();
        if (TextUtils.isEmpty(nicke)) {
            Toast.makeText(this, "请输入邮箱", Toast.LENGTH_SHORT).show();
            return;
        }

        String phone = et_phonr.getText().toString().trim();
        if (TextUtils.isEmpty(phone)) {
            Toast.makeText(this, "请输入你的手机号码", Toast.LENGTH_SHORT).show();
            return;
        }
        String code = et_code.getText().toString().trim();
        if (TextUtils.isEmpty(code)) {
            Toast.makeText(this, "请输入手机验证码", Toast.LENGTH_SHORT).show();
            return;
        }

        String password = et_password.getText().toString().trim();
        if (TextUtils.isEmpty(password)) {
            Toast.makeText(this, "密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }

        String comfrimpassword = et_comfirmpassword.getText().toString().trim();
        if (TextUtils.isEmpty(comfrimpassword)) {
            Toast.makeText(this, "确认密码不能为空", Toast.LENGTH_SHORT).show();
            return;
        }
        if(!password.equals(comfrimpassword)){
            Toast.makeText(this, "两次输入的密码不一致！", Toast.LENGTH_SHORT).show();
            return;
        }

        final JSONObject jsonObject = new JSONObject();
        try {
            jsonObject.put("phone",phone);
            jsonObject.put("smscode",code);
            jsonObject.put("username",name);
            jsonObject.put("password",password);
            jsonObject.put("email",nicke);
        } catch (JSONException e) {
            e.printStackTrace();
        }
        MediaType mediaType = MediaType.parse("application/json;charset=utf-8");
        final RequestBody requestBody =RequestBody.create(mediaType,jsonObject.toString());
        Request request = new Request.Builder()
                .post(requestBody)
                .url(APIConfig.RegisterUrl)
                .build();
        Call call = client.newCall(request);
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {
                Log.d("onFailure", "onFailure: "+e.getMessage());
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                Message msg = new Message();
                msg.what=0;
                msg.obj = result;
                handler.sendMessage(msg);
            }
        });
    }



}
